//
//  MSRegistSecondViewController.m
//  SocietySale
//
//  Created by Mike on 16/11/1.
//  Copyright © 2016年 Mike. All rights reserved.
//

#import "MSRegistSecondViewController.h"
#import "MSRegistSecondTableVC.h"
#import "MSRegistSuccessViewController.h"
#import "MSLoginViewController.h"
#import "MSUploadCardViewController.h"

@interface MSRegistSecondViewController ()
{
    NSInteger        timeNum;          // 倒计时数字
    NSTimer          *countdownTimer;  //验证码倒计时
}

@property (nonatomic, copy)   NSString    *btnTitle;
@property (nonatomic, strong) UIButton    *verifyBtn;
@property (nonatomic, strong) UIButton    *doneBtn;
@property (nonatomic, strong) UITextField *passwordTextField;
@property (nonatomic, strong) UITextField *verifyTextField;
@property (nonatomic, strong) MSRegistSecondTableVC *tableVC;
@end

@implementation MSRegistSecondViewController

- (void)dealloc
{
    for(UIView* view in [self.contentView subviews])
    {
        [view removeFromSuperview];
    }
    
    self.contentView=nil;
    self.VctrID=nil;
    
    if(countdownTimer!=nil)
    {
        [countdownTimer invalidate];
        countdownTimer = nil;
    }
}

- (void)initNavigationBar{
    [super initNavigationBar];
    leftBarBtn.hidden = NO;
    if (self.registType == MSRegistType_Regist) {
        titleLable.text = @"设置密码";
        _btnTitle = @"完成注册";
    }
    else{
        titleLable.text = @"设置新密码";
        _btnTitle = @"完成";
    }
//    self.phoneNum = @"18343249324";
}

- (void)initUI{
    self.tableVC = [[MSRegistSecondTableVC alloc] initWithStyle:UITableViewStyleGrouped];
    self.tableVC.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-KNavBarHeight);
    self.tableVC.enableRefresh = NO;
    self.tableVC.enableRequest = NO;
    self.tableVC.delegate = (id)self;
    self.tableVC.tableView.scrollEnabled = NO;
    self.tableVC.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.contentView addSubview:self.tableVC.view];
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 60)];
    headerView.backgroundColor = kDefaultViewBackgroundColor;
    self.tableVC.tableView.tableHeaderView = headerView;
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(12, 0, 290, 60)];
    titleLabel.text = @"短信验证码已发送至：";
    titleLabel.textColor = UIColorFromRGB(0x222222);
    titleLabel.font = HeitiFont(13);
    [headerView addSubview:titleLabel];
    
    NSMutableAttributedString *titleAttStr = [[NSMutableAttributedString alloc] initWithString:@"短信验证码已发送至：" attributes:@{NSFontAttributeName:HeitiFont(13),NSForegroundColorAttributeName:kLightGrayColor}];
    NSAttributedString *phoneStr = [[NSAttributedString alloc] initWithString:self.phoneNum attributes:@{NSFontAttributeName:HeitiFont(13)}];
    [titleAttStr appendAttributedString:phoneStr];
    
    NSAttributedString *spaceStr = [[NSAttributedString alloc] initWithString:@" " attributes:@{NSFontAttributeName:HeitiFont(13)}];
    [titleAttStr insertAttributedString:spaceStr atIndex:titleAttStr.length-8];
    [titleAttStr insertAttributedString:spaceStr atIndex:titleAttStr.length-4];
    
    titleLabel.attributedText = titleAttStr;

    //布局footerView
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 100)];
    footerView.backgroundColor = kDefaultViewBackgroundColor;
    self.tableVC.tableView.tableFooterView = footerView;
    
    self.doneBtn = [[GXButton alloc] initWithFrame:CGRectMake(12, 25, SCREEN_WIDTH-24, 45)];
    self.doneBtn.titleLabel.font = HeitiFont(16);
    [self.doneBtn setTitle:_btnTitle forState:UIControlStateNormal];
    [self.doneBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.doneBtn.backgroundColor = kBlueColor;
    self.doneBtn.layer.cornerRadius = 2;
    [self.doneBtn addTarget:self action:@selector(doneClick) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:self.doneBtn];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapClick)];
    [self.contentView addGestureRecognizer:tap];
}

- (void)testDataFunc{
    NSString *passwordPlace = self.registType == MSRegistType_Regist? @"请设置不少于6位密码":@"请设置不少于6位新密码";
    self.tableVC.dataArray = [NSMutableArray arrayWithArray:
                              @[[DOKeyValue key:@"yanzheng" value:@""placeHolder:@"请输入验证码"],
                                [DOKeyValue key:@"password" value:@""placeHolder:passwordPlace]
                                ]
                              ];
    
    MSEditCell *cell1 = (MSEditCell *)[self.tableVC.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0]];
    MSEditCell *cell2 = (MSEditCell *)[self.tableVC.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForItem:1 inSection:0]];
    
    self.verifyTextField = cell1.inputField;
    self.passwordTextField = cell2.inputField;
    
    _verifyBtn = cell1.verifyBtn;
    [_verifyBtn addTarget:self action:@selector(getVerifyNum) forControlEvents:UIControlEventTouchUpInside];
    
    self.verifyTextField.delegate = (id)self;
    self.passwordTextField.delegate = (id)self;
    
    timeNum = 60;
    countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 block:^{
        [self countdown];
    } repeats:YES];
    [countdownTimer fire];
}

- (void)updateViewController:(NSNotification *)note {
    NSDictionary *responseDic = note.userInfo;
    if (responseDic[Receiver]==self.VctrID) {
        if (responseDic[@"VerifyMobile"]!=nil) {//注册验证码
            __weak MSRegistSecondViewController *weakself = self;
            countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 block:^{
                [weakself countdown];
            } repeats:YES];
            timeNum = 60;
        }
        if (responseDic[@"ForgetPassword"]!=nil) {//修改密码验证码
            __weak MSRegistSecondViewController *weakself = self;
            countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 block:^{
                [weakself countdown];
            } repeats:YES];
            timeNum = 60;
        }
        if (responseDic[@"Regist"]!=nil) {//注册成功,去上传名片
            MSUploadCardViewController *vc = [[MSUploadCardViewController alloc] init];
            vc.isRegist = YES;
            [rootNavigation pushViewController:vc animated:YES];
            
            NSDictionary *params = @{@"userName":self.phoneNum,
                                     @"password":self.passwordTextField.text};
            [netEngine requestLoginWithTarget:self.VctrID hudView:nil params:params];
        }
        if (responseDic[@"ResetPassword"]!=nil) {
            if (self.registType == MSRegistType_ForgetPassword){//忘记密码
                [rootNavigation popToRootViewControllerAnimated:YES];
                [HDUtil showMessage:@"修改密码成功"];
            }
            else if (self.registType == MSRegistType_ResetPassword){//重置密码成功
                [HDUtil showMessage:@"重新设置成功"];
                
                NSArray *viewControllers = [rootNavigation viewControllers];
                for (int i =0; i<viewControllers.count; i++) {
                    UIViewController *vc = viewControllers[i];
                    if ([vc isKindOfClass:[MSLoginViewController class]]) {
                        [rootNavigation popToViewController:viewControllers[i] animated:YES];
                        return;
                    }
                }
                if (![viewControllers containsObject:[MSLoginViewController class]]) {
                    [rootNavigation popToRootViewControllerAnimated:YES];
                }
            }
        }
    }
}

#pragma mark - getVerifyNum
- (void)getVerifyNum{
    if (self.registType == MSRegistType_Regist){
        [netEngine requestVerifyMobileWithTarget:self.VctrID hudView:self.contentView mobile:self.phoneNum];
    }
    else{
        [netEngine requestForgetPasswordWithTarget:self.VctrID hudView:self.contentView mobile:self.phoneNum];
    }
    [_verifyBtn setUserInteractionEnabled:NO];
    __weak MSRegistSecondViewController *weakself = self;
    countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 block:^{
        [weakself countdown];
    } repeats:YES];
    timeNum = 60;
}

- (void)countdown{
    if (timeNum > 0) {
        NSString *string = [NSString stringWithFormat:@"%lds后重发",(long)timeNum];
        _verifyBtn.titleLabel.text = string;
        [_verifyBtn setTitle:string forState:UIControlStateNormal];
        [_verifyBtn setUserInteractionEnabled:NO];
        [_verifyBtn setTitleColor:kDarkGrayColor forState:UIControlStateNormal];
        _verifyBtn.backgroundColor = kDefaultViewBackgroundColor;
        _verifyBtn.layer.borderColor = kDefaultViewBackgroundColor.CGColor;
        timeNum--;
    } else {
        timeNum = 60;
        [_verifyBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [_verifyBtn setUserInteractionEnabled:YES];
        [_verifyBtn setTitleColor:kBlueColor forState:UIControlStateNormal];
        _verifyBtn.layer.borderColor = kBlueColor.CGColor;
        _verifyBtn.backgroundColor = [UIColor clearColor];
        
        [countdownTimer invalidate];
        countdownTimer = nil;
        [countdownTimer setFireDate:[NSDate distantFuture]];
    }
}

- (void)doneClick{
    if ([[self.verifyTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0) {
        [HDUtil showMessage:@"请输入验证码"];
        return;
    }
    if ([[self.passwordTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0) {
        [HDUtil showMessage:@"请输入密码"];
        return;
    }
    NSDictionary *params = @{@"userName":self.phoneNum,
                             @"password":self.passwordTextField.text,
                             @"smsVerifyCode":self.verifyTextField.text};
    if (self.registType == MSRegistType_Regist) {//去上传名片
        [netEngine requestRegistWithTarget:self.VctrID hudView:self.contentView params:params];
//        MSUploadCardViewController *vc = [[MSUploadCardViewController alloc] init];
//        vc.isRegist = YES;
//        [rootNavigation pushViewController:vc animated:YES];
        
//        NSUserDefaults *defaultes = [NSUserDefaults standardUserDefaults];
//        [defaultes setObject:@"y" forKey:LoginState];
//        [defaultes synchronize];
    }
    else if (self.registType == MSRegistType_ForgetPassword){//忘记密码
        [netEngine requestResetPasswordWithTarget:self.VctrID hudView:self.contentView params:params];
//        [rootNavigation popToRootViewControllerAnimated:YES];
//        [HDUtil showMessage:@"修改密码成功"];
    }
    else if(self.registType == MSRegistType_ResetPassword){
        [netEngine requestResetPasswordWithTarget:self.VctrID hudView:self.contentView params:params];
        
//        NSArray *viewControllers = [rootNavigation viewControllers];
//        for (int i =0; i<viewControllers.count; i++) {
//            UIViewController *vc = viewControllers[i];
//            if ([vc isKindOfClass:[MSLoginViewController class]]) {
//                [rootNavigation popToViewController:viewControllers[i] animated:YES];
//                return;
//            }
//        }
//        if (![viewControllers containsObject:[MSLoginViewController class]]) {
//            [rootNavigation popToRootViewControllerAnimated:YES];
//        }
    }
}

- (void)tapClick{
    [self.view endEditing:YES];
}

@end
